﻿using Framework.Core.Consts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Security.Claims;

namespace Framework.AspNetCore.User
{
	public class CurrentUser : ITransientDependency
	{
		private static readonly Claim[] EmptyClaimsArray = new Claim[0];

		public virtual string Id => _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

		public long UserId
		{
			get => long.Parse(_principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value);
		}

		public virtual string UserName => _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimConst.Name)?.Value;

		public bool SuperAdmin
		{
			get => _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimConst.Name)?.Value == CommonConst.SuperAdmin;
		}

		public virtual string Account => _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimConst.Account)?.Value;

		public virtual long OrgId
		{
			get
			{
				var orgId = _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimConst.OrgId)?.Value;
				return string.IsNullOrWhiteSpace(orgId) ? 0 : long.Parse(orgId);
			}
		}

		public virtual string OrgName => _principalAccessor.Principal?.Claims?.FirstOrDefault(c => c.Type == ClaimConst.OrgName)?.Value;

		private readonly ICurrentPrincipalAccessor _principalAccessor;

		public CurrentUser(ICurrentPrincipalAccessor principalAccessor)
		{
			_principalAccessor = principalAccessor;
			var tmp = _principalAccessor.Principal?.Claims.ToList();
		}

		public virtual Claim[] FindClaims(string claimType)
		{
			return _principalAccessor.Principal?.Claims.Where(c => c.Type == claimType).ToArray();
		}

		public virtual Claim FindClaim(string claimType)
		{
			return _principalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == claimType);
		}
	}
}
